﻿using Core.IService;
using Core.Models;
using Core.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.WebApi.Controllers.SystemControllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DictionaryTypeController : ControllerBase
    {
        public DictionaryTypeController(ISysDictionaryTypeService dictTypeService)
        {
            DictTypeService = dictTypeService;
        }

        public ISysDictionaryTypeService DictTypeService { get; }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<SysDictionaryType>>> GetList()
        {
            var list = await DictTypeService.GetList().ToListAsync();
            return list;
        }

        [HttpPost]
        public async Task<ActionResult<SysDictionaryType>> Post(DictionaryTypePostVM vm)
        {
            SysDictionaryType type = new SysDictionaryType
            {
                Name = vm.Name
            };
            var rst = await DictTypeService.AddAsync(type);
            return CreatedAtAction("GetDictionaryType", new { id = type.Id }, type);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<SysDictionaryType>> GetDictionaryType(int id)
        {
            var type = await DictTypeService.GetEntityAsync(id);

            if (type == null)
            {
                return NotFound();
            }

            return type;
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> Put(int id, DictionaryTypePostVM type)
        {
            if (id != type.Id)
            {
                return BadRequest();
            }
            var dictType = new SysDictionaryType { Id = id, Name = type.Name };

            try
            {
                await DictTypeService.EditAsync(dictType);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (DictTypeService.Exists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
           
            await DictTypeService.MarkDeleteAsync(id);

            return NoContent();
        }

    }
}
